package com.jd.cs.common;

import com.jd.cs.anotation.NotRepeatSubmit;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author: lizhiwei
 * @date: 2020-07-25 21:00
 **/
public class ApiUtil {

    /**
     * 按参数名升续拼接参数
     *
     * @param request
     * @return
     */
    public static String concatSignString(HttpServletRequest request) {
        Map<String, String> parameterMap = new TreeMap<>();
        request.getParameterMap().forEach((key, value) -> parameterMap.put(key, value[0]));
        return concatSignString(parameterMap);
    }

    public static String concatSignString(Map<String, String> map) {
        Map<String, String> parameterMap = new TreeMap<>();
        map.forEach(parameterMap::put);
        // 按照key升续排序，然后拼接参数
        StringBuilder sb = new StringBuilder();
        parameterMap.forEach((key, value) -> {
            if (StringUtils.isEmpty(value)) {
                return;
            }
            sb.append(key).append("=").append(value);
        });
        return sb.toString();
    }

    /**
     * 获取方法上的@NotRepeatSubmit注解
     *
     * @param handler
     * @return
     */
    public static NotRepeatSubmit getNotRepeatSubmit(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            NotRepeatSubmit annotation = method.getAnnotation(NotRepeatSubmit.class);
            return annotation;
        }

        return null;
    }
}